import { FC, createContext, useEffect, useState } from 'react';
import { Space } from 'antd';
import request from 'umi-request';
import Form from './components/Form';
import Table from './components/Table';
import Modal from './components/Modal';

export const context = createContext({
  dataSource: [],
  count: 0,
  currentPage: 1,
  onSizeChange(page: number, pageSize: number) {},
  onSearchChange(values: any) {},
  onRemove(id: string) {},
  isModalOpen: false,
  modalOpen(type: string, item?: ItemType) {},
  addStudent(values: any) {},
  modalClose() {},
  type: 'add',
  itemData: {
    _id: undefined,
    birthday: undefined,
  },
  editStudent(values: any) {},
});

interface ItemType {
  birthday: number;
  city: string;
  name: string;
  sex: string;
  _id: string;
}

const Index: FC = () => {
  // 数据源
  const [dataSource, setDataSource] = useState([]);
  // 总共由几条数据
  const [count, setCount] = useState(0);
  // 当前是第几页
  const [currentPage, setCurrentPage] = useState(1);
  // 每页是几条
  const [pageSize, setPageSize] = useState(10);
  // 用于搜索的对象
  const [search, setSearch] = useState({});
  // 控制模态框的显示
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 控制是新增还是编辑
  const [type, setType] = useState('add');
  // 编辑的原始数据
  const [itemData, setItemData] = useState<any>({});

  // 请求列表的接口
  const getData = () => {
    request('http://www.pudge.wang:3333/api/students/list', {
      params: {
        page_size: pageSize,
        current_page: currentPage,
        ...search,
      },
    }).then((res) => {
      if (res.status === 0) {
        console.log(res.result);

        // antd的table希望每一条数据都有一个key属性
        const arr = res.result.map((item: ItemType) => ({
          ...item,
          key: item._id,
        }));
        setDataSource(arr);
        setCount(res.count);
      }
    });
  };

  useEffect(() => {
    getData();
  }, [currentPage, pageSize, search]);

  // 当子组件切换页码和条数的时候，来改变父组件的两个变量
  const onSizeChange = (page: number, pageSize: number) => {
    // console.log(page, pageSize);
    setCurrentPage(page);
    setPageSize(pageSize);
  };

  const onSearchChange = (values: any) => {
    // console.log('values', values);
    setSearch(values);
  };

  // 删除的事件
  const onRemove = (id: string) => {
    // 调删除接口
    request
      .post('http://www.pudge.wang:3333/api/students/del', {
        data: { id },
      })
      .then((res) => {
        // console.log(res);
        if (res.status === 0) {
          getData();
        }
      });
  };

  // 打开模态框
  const modalOpen = (type: string, item?: ItemType) => {
    setIsModalOpen(true);
    setType(type);
    if (type === 'edit') {
      setItemData({ ...item });
    } else {
      setItemData({});
    }
  };
  // 打开模态框
  const modalClose = () => {
    setIsModalOpen(false);
  };

  // 新增接口
  const addStudent = (values: any) => {
    request
      .post('http://www.pudge.wang:3333/api/students/add', {
        data: values,
      })
      .then((res) => {
        if (res.status === 0) {
          setIsModalOpen(false);
          getData();
        }
      });
  };

  const editStudent = (values: any) => {
    request
      .post('http://www.pudge.wang:3333/api/students/update', {
        data: values,
      })
      .then((res) => {
        if (res.status === 0) {
          setIsModalOpen(false);
          getData();
        }
      });
  };

  return (
    <context.Provider
      value={{
        dataSource,
        count,
        currentPage,
        onSizeChange,
        onSearchChange,
        onRemove,
        isModalOpen,
        modalOpen,
        modalClose,
        addStudent,
        type,
        itemData,
        editStudent,
      }}
    >
      <Space direction="vertical" style={{ display: 'flex' }}>
        <Form />
        <Table />
      </Space>
      <Modal />
    </context.Provider>
  );
};

export default Index;
